package bis;

import java.util.*;

public class FLShoppingCart {

    HashMap items = null;
    int numberOfItems = 0;
    String bookId = null;

    public FLShoppingCart() {
        items = new HashMap();
    }

    public void setadd1(String bookId) {
        this.bookId=bookId;
    }

    public void setadd2(FLBook book) {
        if (items.containsKey(bookId)) {
            FLShoppingCartItem scitem = (FLShoppingCartItem) items.get(bookId);
            scitem.incrementQuantity();
        } else {
            FLShoppingCartItem newItem = new FLShoppingCartItem(book);
            items.put(bookId, newItem);
        }

        numberOfItems++;
    }

    public void setremove(String bookId) {
        if (items.containsKey(bookId)) {
            FLShoppingCartItem scitem = (FLShoppingCartItem) items.get(bookId);
            scitem.decrementQuantity();

            if (scitem.getQuantity() <= 0) {
                items.remove(bookId);
            }

            numberOfItems--;
        }
    }

    public Collection getItems() {
        return items.values();
    }

    @Override
    protected void finalize() throws Throwable {
        items.clear();
    }

    public int getNumberOfItems() {
        return numberOfItems;
    }

    public double getTotal() {
        double amount = 0.0;

        for (Iterator i = getItems().iterator(); i.hasNext();) {
            FLShoppingCartItem item = (FLShoppingCartItem) i.next();
            FLBook bookDetails = (FLBook) item.getItem();

            amount += item.getQuantity() * bookDetails.getPrice();
        }
        return isroundOff(amount);
    }

    private double isroundOff(double x) {
        long val = Math.round(x * 100); // cents
        return val / 100.0;
    }

    public void isclear() {
        items.clear();
        numberOfItems = 0;
    }
}

